<template>
  <div class="content">
    <div>
      <div class="btns">
        <button v-if="!isStart" type="primary" size="mini" @click="onEnableClick">启动UDP服务</button>
        <button v-else type="warn" size="mini" @click="onDisableClick">停止UDP服务</button>
      </div>
      <div class="status">{{ statusMessage }}</div>
	  
       <div class="box-wrapper" @click="toggleLogCounterCondition">
              <div class="boxdds" ref="messageBox" style="max-height: 300px; overflow-y: auto;">
                <div v-for="(item, index) in reversedMessages" :key="item.ids + '-' + index" 
                     class="item" 
                     :style="{ color: (index + 1) % 5 === 0 ? 'red' : 'black' }">
                  <div class="info" v-if="item.host && item.port">
                    <span class="label">编号：{{ item.ids }}</span>
                    <span class="label">主机：{{ item.host }}</span>
                    <span class="label">端口：{{ item.port }}</span>
                  </div>
                  <div class="msg" v-if="item.msg">消息：{{ item.msg }}</div>
                </div>
              </div>
            </div>
          </div>


    <div class="input-container">
      <div class="input-group">
        <label>目标IP:</label>
        <div class="input-wrapper">
          <uni-easyinput 
            v-model="serverIp" 
            placeholder="服务器IP地址" 
            @focus="showServerIpHistory = true" 
            @blur="hideServerIpHistory" 
            @input="updateServerIpHistory" />
          <ul v-if="showServerIpHistory && serverIpHistory.length" class="history-list">
            <li v-for="ip in serverIpHistory" :key="ip" @click="selectServerIp(ip)">
              {{ ip }}
            </li>
          </ul>
        </div>
      </div>

      <div class="input-group">
        <label>目标端口:</label>
        <div class="input-wrapper">
          <uni-easyinput 
            v-model="sendport" 
            placeholder="服务器端口" 
            type="number" 
            @focus="showsendportHistory = true" 
            @blur="hidesendportHistory" 
            @input="updatesendportHistory" />
          <ul v-if="showsendportHistory && sendportHistory.length" class="history-list">
            <li v-for="port in sendportHistory" :key="sendport" @click="selectsendport(sendport)">
              {{ sendport }}
            </li>
          </ul>
        </div>
      </div>

      <div class="input-group">
        <label>接收端口:</label>
        <div class="input-wrapper">
          <uni-easyinput 
            v-model="recport" 
            placeholder="本机接收端口" 
            type="number" 
            @focus="showrecportHistory = true" 
            @blur="hiderecportHistory" 
            @input="updaterecportHistory" />
          <ul v-if="showrecportHistory && recportHistory.length" class="history-list">
            <li v-for="recport in recportHistory" :key="recport" @click="selectrecport(recport)">
              {{ recport }}
            </li>
          </ul>
        </div>
      </div>

      <div class="input-group">
        <label>消息内容:</label>
        <uni-easyinput v-model="msg" type="textarea" auto-height placeholder="请输入内容"></uni-easyinput>
      </div>
      
      <button @click="onSendClick">发送消息</button>
    </div>
  </div>
</template>

<script>
	import fs from 'fs';
import { UDPServer } from '@/uni_modules/uts-udp';
import { UDPClient } from '@/uni_modules/uts-udp';
import Vue from 'vue';
import { mapState, mapMutations } from 'vuex';
let server = null;
let worker = null;
export default {
	  onShow() {
	    // 每次页面显示时执行的逻辑
	    console.log('页面被显示');
	  },
	  onHide() {
	    // 每次页面隐藏时执行的逻辑
	    console.log('页面被隐藏');
	  },
  data() {
    return {
      isStart: false,
	  statusMessage: 'UDP服务未启动',
	  isAutoStart: false, 
      
      recport: 9091,
      msg: '',
      messages: [],
	  logCounter: 0, // 日志计数器
	  logCounterCondition: 5, // 默认条件为5
      messageCounter: 0,
	        errorCounter: 0, // 添加异常计数器
	        maxRetries: 2, // 设置最大重试次数
      serverIpHistory: [],
      sendportHistory: [],
      recportHistory: [],
      showServerIpHistory: false,
      showsendportHistory: false,
      showrecportHistory: false,
	  originalConsoleError: console.error,
    };
  },
  computed: {
    reversedMessages() {
      return this.messages.slice().reverse();
    },
	...mapState({
	sendMessages: state => state.sendMessages, 
	serverIp: state => state.serverIp,
	sendport: state => state.sendport,
	  }),
	      serverIp: {
	        get() {
	          return this.$store.state.serverIp;
	        },
	        set(value) {
	          this.$store.commit('setServerIp', value);
	        }
	      },
	      sendport: {
	        get() {
	          return this.$store.state.sendport;
	        },
	        set(value) {
	          this.$store.commit('setSendport', value);
	        }
	      }
	},
  watch: {
	    sendMessages: {
	      handler(newMessages) {
	        if (newMessages.length) {
	          this.jsonmsgsend = newMessages[newMessages.length - 1];
			  
	          this.onSendudp(this.jsonmsgsend);
	        }
	      },
	      deep: true, // 深度监听数组变化
	      immediate: true, // 页面加载时立即执行一次 handler
	    },
    recport(newPort, oldPort) {
      if (newPort !== oldPort) {
        this.restartUdpServer();
      }
    }
},
  methods: {
	      ...mapMutations(['setServerIp', 'setSendport']),
	        
	           updateServerIpHistory() {
	             if (!isNaN(this.serverIp) && !this.serverIpHistory.includes(this.serverIp)) {
	               this.serverIpHistory.push(this.serverIp);
	               this.setServerIp(this.serverIp);
	               this.saveConfig();
	             }
	           },
	      
	        updatesendportHistory() {
	              const sendportNumber = parseInt(this.sendport, 10);
	              if (!isNaN(sendportNumber) && !this.sendportHistory.includes(sendportNumber)) {
	                this.sendportHistory.push(sendportNumber);
	                this.sendportHistory = [...new Set(this.sendportHistory)]; // 确保唯一性
	                this.setSendport(sendportNumber);
	                this.saveConfig();
	              } else {
	                console.error('端口号无效或已存在:', this.sendport);
	              }
	            },
	       toggleLogCounterCondition() {
	            if (this.logCounterCondition === 5) {
	              this.logCounterCondition = 0;
	            } else {
	              this.logCounterCondition = 5;
	            }
	          },
	        loadConfig() {
	          try {
	            const config = uni.getStorageSync('config');
	            if (config) {
	              const parsedConfig = typeof config === 'string' ? JSON.parse(config) : config;
	              
	              this.serverIp = parsedConfig.serverIp || this.serverIp;
	              this.sendport = parseInt(parsedConfig.sendport, 10) || this.sendport;
	              this.recport = parseInt(parsedConfig.recport, 10) || this.recport;
				  this.serverIpHistory = [...new Set(this.serverIpHistory)];
				          this.sendportHistory = [...new Set(this.sendportHistory)];
				          this.recportHistory = [...new Set(this.recportHistory)];
	            } else {
	              this.serverIp = 192; // 默认IP的部分（请根据实际需求调整）
	              this.sendport = 9091;
	              this.recport = 9091;
	              this.saveConfig(); // 保存默认配置
	            }
	          } catch (err) {
	            console.error('加载配置失败:', err);
	          }
	        },
	      
	        saveConfig() {
	          const config = {
	            serverIp: this.serverIp,
	            sendport: this.sendport,
	            recport: this.recport,
	          };
	          try {
	            uni.setStorageSync('config', config);
	            console.log('配置文件已保存');
	          } catch (err) {
	            console.error('保存配置文件失败:', err);
	          }
	        },
    incrementMessageCounter() {
      this.messageCounter = (this.messageCounter + 1) % 101;
    },
	async restartUdpServer() {
	      if (this.isStart) {
	        await this.onDisableClick();
	      }
	      this.onEnableClick();
	    },
		
async onSendudp(jsonmsgsend) {
  this.incrementMessageCounter();
  this.messages.push(jsonmsgsend);
 
	      this.logCounter++; // 递增日志计数器
	
	      if (this.logCounter >= this.logCounterCondition) {
	        this.clearLogCache(); // 达到20条日志时清空缓存
	      }

  try {
    await new Promise((resolve, reject) => {
      UDPClient.send({
        host: this.serverIp,
        port: this.sendport,
        receiveTimeout: 2000,
        msg: JSON.stringify(jsonmsgsend), // 将消息对象转换为字符串
        enableRecive: false,
        onceReceive: (data) => {
          data.id = this.messageCounter;
          this.messages.push(data);
          resolve();
        },
        onError: (error) => {
          console.error(error);
          reject(error);
        },
        onceReceiveTimeout: () => {
          console.warn('服务器超时未回复');
          reject(new Error('Timeout'));
        },
      });
    });
  } catch (error) {
    console.error('消息发送失败:', error);
  }
},

    async onSendClick() {
			this.incrementMessageCounter();
		  const messageData = {
			ids: 1,
			msg: this.msg.trim() !== '' ? this.msg : '[空消息]',
		  };
		  console.error(this.sendport);
		  this.messages.push(messageData);
		        this.logCounter++; // 递增日志计数器
		  
		        if (this.logCounter >= this.logCounterCondition) {
		          this.clearLogCache(); // 达到20条日志时清空缓存
		        }
		  UDPClient.send({
			host: this.serverIp,
			port: this.sendport,
			receiveTimeout: 1000,
			msg: this.msg,
			enableRecive: false,
			onceReceive: (data) => {
			  data.id = this.messageCounter;
			  this.messages.push(data);
			},
			onError: (error) => {
			  console.error(error);
			},
			onceReceiveTimeout: () => {
			  console.warn('服务器超时未回复');
			},
      });
    },
	    clearLogCache() {
	      //console.clear(); // 清空控制台日志
	      this.messages = []; // 清空消息缓存
	      this.logCounter = 0; // 重置日志计数器
	    },
    async onEnableClick() {
		 let errorCounter = 0; 
      if (this.isStart) return;
    
      try {
        if (server) {
          await server.stop();
		  server = null;
          this.isStart = false;
        }
        const port = parseInt(this.recport, 10);
		
        if (isNaN(port)) {
          throw new Error('接收端口无效，请输入有效的数字端口。');
		  this.root.root.emit('logEvent', '接收端口无效，请输入有效的数字端口。');
        }
		let messageTimeout;
        server = new UDPServer(port);
        server.listener(
          (data) => {
            this.incrementMessageCounter();
            data.ids = this.messageCounter;
            this.messages.push(data);
			this.$store.commit('jsonmsg',data)
			this.logCounter++; // 递增日志计数器
				
			if (this.logCounter >= this.logCounterCondition) {
			  this.clearLogCache(); // 达到20条日志时清空缓存
			}
            this.$nextTick(() => {
              this.scrollToTop();
            });
			
            const sendport = parseInt(this.sendport, 10);
            
            if (isNaN(sendport)) {
              console.error('发送端口无效，无法发送消息。');
			  this.root.root.emit('logEvent', '发送端口无效，无法发送消息。');
            } else {
              //server.send(`已收到消息：${data.msg}`, data.host, sendport);
            }
			    // 重新设置定时器
			let startTime = Date.now();

			setTimeout(() => {
			  let elapsedTime = Date.now() - startTime;
			  //console.log(`预计时间: 6000ms, 实际时间: ${elapsedTime}ms`);
			  this.$store.commit('jsonmsg', {});
			}, 6000);
          },
          (error) => {
              console.error(error);
              this.isStart = false;
			  this.statusMessage = 'UDP服务异常';
			  this.root.root.emit('logEvent', 'UDP服务异常');
			  this.errorCounter++; 
			  if (this.errorCounter > 2) {
				this.statusMessage = '请重启应用';
				this.root.root.emit('logEvent', '请重启应用');
				
			  } else {
				this.statusMessage = 'UDP启动异常';
			  }//
          }
        );
		messageTimeout = setTimeout(() => {
		  const emptyData = {}; // 创建一个空对象
		  this.$store.commit('jsonmsg', emptyData); // 提交空对象
		}, 3000);
        this.isStart = true;
		if (this.isAutoStart) {
		      this.statusMessage = 'UDP已自动启动';
		      this.isAutoStart = false;  // 重置标志以防后续混淆
		    } else {
		      this.statusMessage = 'UDP服务已启动';
		    }
      } catch (error) {
        console.error('启动UDP服务失败:', error);
        this.isStart = false;
		 errorCounter++; // 记录异常次数
		this.statusMessage = 'UDP服务启动异常';
		          if (errorCounter > 2) {
		            this.statusMessage = '请重启应用';
		          } else {
		            this.statusMessage = 'UDP服务启动异常';
		          }
      }
    },

    onDisableClick() {
        if (server) {
          server.stop();
          server = null; // 确保实例被释放
        }
      this.isStart = false;
	  this.statusMessage = 'UDP服务未启动';
    },
    scrollToTop() {
      const box = this.$refs.messageBox;
      box.scrollTop = 0;
    },
    updaterecportHistory() {
          const recportNumber = parseInt(this.recport, 10);
          if (!isNaN(recportNumber) && !this.recportHistory.includes(recportNumber)) {
            this.recportHistory.push(recportNumber);
            this.recportHistory = [...new Set(this.recportHistory)]; // 确保唯一性
            this.saveConfig();
          } else {
            console.error('接收端口号无效或已存在:', this.recport);
          }
        },

    selectServerIp(ip) {
      this.serverIp = ip;
      this.showServerIpHistory = false;
    },
    hideServerIpHistory() {
      setTimeout(() => {
        this.showServerIpHistory = false;
		this.saveConfig();
      }, 1000);
    },
    updatesendportHistory() {
      if (!this.sendportHistory.includes(this.sendport) && this.sendport) {
        this.sendportHistory.push(this.sendport);
      }
    },
    selectsendport(port) {
      this.sendport = port;
      this.showsendportHistory = false;
    },
    hidesendportHistory() {
      setTimeout(() => {
        this.showsendportHistory = false;
		this.saveConfig();
      }, 1000);
    },
	hiderecportHistory() {
	  setTimeout(() => {
	    this.showrecportHistory = false;
		this.saveConfig();  // 保存配置
	  }, 1000);
	},
    updaterecportHistory() {
      if (!this.recportHistory.includes(this.recport) && this.recport) {
        this.recportHistory.push(this.recport);
		 
      }
    },
    selectrecport(port) {
      this.recport = port;
      this.showrecportHistory = false;
    },

  },
  mounted() {
	  this.loadConfig(); 
	  this.isAutoStart = true;
	this.onEnableClick();
    this.scrollToTop();
  }
};
</script>

<style lang="scss" scoped>
.content {
  font-size: 15px;
  position: relative;
}
.btns {
  position: absolute; /* 绝对定位 */
  top: 10px; /* 距离容器顶部 20px */
  right: 20px; /* 距离容器右侧 20px */
  z-index: 10; /* 确保按钮组在其他内容之上 */
  padding: 10px;
}
.box-wrapper {
  position: absolute;
  top: 60px; /* 设置为合适的距离 */
  left: 8px;
  width: 320px; /* 设置框的宽度 */
  height: 290px;
  border: 2px solid #ddd; /* 添加边框 */
  padding: 10px; /* 内部填充 */
  background-color: #fff; /* 背景颜色 */
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); /* 阴影效果 */
  }
.status {
  position: absolute; /* 绝对定位 */
  top: 10px; /* 距离容器顶部 60px */
  right: 230px; /* 距离容器右侧 20px */
  z-index: 10; /* 确保状态信息在其他内容之上 */
  padding: 10px;
  background-color: #fff; /* 设置背景色以便与内容区分 */
  border: 1px solid #ddd; /* 设置边框 */
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); /* 添加阴影效果 */
}
.input-container {
  position: absolute;
  top: 360px;
  right: 20px;
  background-color: #fff;
  padding: 10px;
  border: 1px solid #ddd;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  width: 300px;
}

.input-container uni-easyinput {
  margin-bottom: 10px;
}
.boxdds {
  padding: 1px;

  .item {
    padding: 1px;
    margin-bottom: 0px; /* 缩短 item 之间的距离 */

    .label + .label {
      margin-left: 1px;
    }
  }

  /* 防止最后一个 .item 元素增加额外的 margin */
  .item:last-child {
    margin-bottom: 0;
  }
}

.input-group {
  display: flex;
  align-items: center;
  margin-bottom: 10px;

  label {
    min-width: 90px;
    font-weight: bold;
  }

  .input-wrapper {
    flex: 1;
  }
}

.history-list {
  list-style: none;
  padding: 0;
  margin: 0;
  border: 1px solid #ddd;
  background-color: #fff;
  max-height: 100px;
  overflow-y: auto;
}

.history-list li {
  padding: 8px;
  cursor: pointer;
  border-bottom: 1px solid #ddd;
}

.history-list li:hover {
  background-color: #f0f0f0;
}
</style>
